<template>
  <div class="chart-wrap">
    <div :id="uuidStr" :style="{ height }"></div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, ref, watch } from 'vue'
  import * as echarts from 'echarts'
  import { v4 as uuidv4 } from 'uuid'
  import { useChartResize } from '@/plugins/chartResize'

  type TargetValue = Record<string, any>

  const chartState = useChartResize()

  const emit = defineEmits(['hoverItem', 'clickItem'])

  const uuidStr = ref('')
  uuidStr.value = uuidv4()

  interface Props {
    height?: string
    options?: Record<any, object>
  }
  const props = withDefaults(defineProps<Props>(), {
    height: '350px'
  })

  watch(
    () => props.height,
    () => {
      chart.resize({
        height: Number(props.height.slice(0, -2))
      })
    }
  )

  let chart: any
  onMounted(() => {
    chart = echarts.init(document.getElementById(uuidStr.value) as any)

    chartState.add(chart)

    chart.on('mouseover', function (params: TargetValue) {
      emit('hoverItem', params.name)
    })
    chart.on('click', function (params: TargetValue) {
      emit('clickItem', params.name)
    })
  })

  const setData = (data: TargetValue) => {
    chart.clear()
    chart.setOption(data || props?.options)
  }

  const setOption = (data) => {
    chart.setOption(data || props?.options)
  }

  onUnmounted(() => {
    if (chart != null && chart != '' && chart != undefined) {
      chart.dispose() //销毁
    }

    chartState.clear()
  })

  const resetCharts = () => {
    // 重置图表大小
    chart.resize()
  }

  defineExpose({ resetCharts, setData, setOption })
</script>

<style lang="less" scoped>
  .chart-wrap {
    width: 100%;
  }
</style>
